package models

import (
	"NewEdu/utils"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/redis/go-redis/v9"
)

type TQuestionTemplate struct {
	Id             int       `orm:"column(id);auto"`
	Label          string    `orm:"column(label);size(245);null" description:"密码"`
	Desc           string    `orm:"column(desc);size(245);null" description:"密码"`
	Creattime      time.Time `orm:"column(creattime);" description:"密码"`
	Author         string    `orm:"column(author);size(245);null" description:"密码"`
	AuthorSn       string    `orm:"column(author_sn);size(245);null" description:"密码"`
	Questions      string    `orm:"column(questions);"`
	Kind           int8      `orm:"column(kind);null" description:"0 普通访谈，1 出国访谈"`
	AnalysisPrompt string    `orm:"column(analysis_prompt);"`
}

func (t *TQuestionTemplate) TableName() string {
	return "t_question_template"
}

func init() {

	orm.RegisterModel(new(TQuestionTemplate))
}

// TQuestionTemplate insert a new TUser into database and returns
// last inserted Id on success.
func AddTQuestionTemplate(m *TQuestionTemplate) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	if err != nil {
		return
	}
	var itemJson []byte
	itemJson, _ = json.Marshal(m)
	ctx := context.Background()
	cmd := utils.RedisClient.Set(ctx, fmt.Sprintf("template:%d", m.Id), itemJson, 0)
	_, err = cmd.Result()
	if err != nil {
		fmt.Println("user 写入到redis出错:", err)
		return
	}
	return
}

func UpdateTQuestionTemplate(m *TQuestionTemplate) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Update(m)
	if err != nil {
		return
	}
	var itemJson []byte
	itemJson, _ = json.Marshal(m)
	ctx := context.Background()
	cmd := utils.RedisClient.Set(ctx, fmt.Sprintf("template:%d", m.Id), itemJson, 0)
	_, err = cmd.Result()
	if err != nil {
		fmt.Println("user 写入到redis出错:", err)
		return
	}
	return
}

// GetAllTQuestionTemplate retrieves all TQuestionTemplate matches certain condition. Returns empty list if
// no records exist
func GetAllTemplate() (itemList []*TQuestionTemplate, err error) {
	ctx := context.Background()
	keys, err := utils.RedisClient.Keys(ctx, "template:*").Result()
	if err != nil {
		return nil, err
	}
	for _, key := range keys {
		val, err := utils.RedisClient.Get(ctx, key).Bytes()
		if err == redis.Nil {
			fmt.Printf("Key %s does not exist\n", key)
			continue
		} else if err != nil {
			return nil, err
		}
		var item TQuestionTemplate
		if err := json.Unmarshal(val, &item); err != nil {
			return nil, err
		}
		itemList = append(itemList, &item)
	}
	return itemList, nil
}

func GetTemplateByID(id int) (item *TQuestionTemplate, err error) {
	ctx := context.Background()
	val, err := utils.RedisClient.Get(ctx, fmt.Sprintf("template:%d", id)).Bytes()
	if err == redis.Nil {
		fmt.Printf("Key %s does not exist\n", fmt.Sprintf("template:%d", id))
		return nil, err
	} else if err != nil {
		fmt.Println("template 获取出错:", err)
		return nil, err
	}

	item = &TQuestionTemplate{}
	if err := json.Unmarshal(val, item); err != nil {
		fmt.Printf("data:%s", val)
		fmt.Printf("template json 反序列化出错:%s", err)
		return nil, err
	}
	return item, nil
}

func LoadTemplate2Redis() error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TQuestionTemplate))
	var allItem []*TQuestionTemplate
	counts, err := qs.All(&allItem)
	if err != nil {
		fmt.Println("载入 question 出错", err.Error())
		return err
	}
	fmt.Println("载入 question template 到redis中数为:", counts)
	ctx := context.Background()

	var cursor uint64
	for {
		var keys []string
		var err error
		keys, cursor, err = utils.RedisClient.Scan(ctx, cursor, "template:*", 100).Result()
		if err != nil {
			fmt.Println("template Del写入到redis出错:", err)
			return err
		}
		if len(keys) > 0 {
			_, err := utils.RedisClient.Del(ctx, keys...).Result()
			if err != nil {
				fmt.Println("template Del写入到redis出错:", err)
				return err
			}
		}
		if cursor == 0 {
			break
		}
	}

	var cmd *redis.StatusCmd
	var itemJson []byte
	for _, item := range allItem {
		itemJson, _ = json.Marshal(item)
		cmd = utils.RedisClient.Set(ctx, fmt.Sprintf("template:%d", item.Id), itemJson, 0)
		_, err = cmd.Result()
		if err != nil {
			fmt.Println("user 写入到redis出错:", err)
			return err
		}

	}

	return nil
}
